package com.mach.platform.utils.security;

import com.mach.platform.domain.CustomizeUserInfo;
import com.mach.platform.domain.base.Account;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import java.util.Collection;


/**
  * @Description: 安全工具类
  *
  * @date  2018/5/11 0011   15:03
  * @author Administrator
  */
public class SecurityUtils {

	/**
	 * 取得Authentication, 如当前SecurityContext为空时返回null.
	 */
	private static Authentication getAuthentication() {
		SecurityContext context = SecurityContextHolder.getContext();

		if (context == null) {
			return null;
		}

		return context.getAuthentication();
	}

	/**
	 * 取得当前用户的登录名, 如果当前用户未登录则返回空字符串.
	 */
	public static String getCurrentUserName() {
		Authentication authentication = getAuthentication();

		if (authentication == null || authentication.getPrincipal() == null) {
			return "";
		}

		return authentication.getName();
	}

	/**
	 *  把当前 登录用户的 信息 转为 account 返回
	 * @return
	 */
	public static Account getCurrentUserByAccountDomain ( ) {

		CustomizeUserInfo currentUser = getCurrentUser();
		Account account = new Account();
		account.setId(currentUser.getId());
		account.setUsername(currentUser.getUsername());

		return account;
	}

	/**
	 *  从CustomizeUserInfo  获取 登陆者的信息
	 * 取得当前用户, 返回值为CustomizeUserInfoUserInfo类或其子类, 如果当前用户未登录则返回null.
	 */
	@SuppressWarnings("unchecked")
	public static <T extends CustomizeUserInfo> T getCurrentUser ( ) {
		Authentication authentication = getAuthentication();

		if (authentication == null) {
			return null;
		}

		Object principal = authentication.getPrincipal();
		if (!(principal instanceof CustomizeUserInfo)) {
			return null;
		}

		return (T) principal;
	}

	/**
	 * 取得当前用户登录IP, 如果当前用户未登录则返回空字符串.
	 * 0:0:0:0:0:0:0:1是ipv6的表现形式，对应ipv4来说相当于127.0.0.1
	 */
	public static String getCurrentUserIp() {
		Authentication authentication = getAuthentication();

		if (authentication == null) {
			return "";
		}

		Object details = authentication.getDetails();
		if (!(details instanceof WebAuthenticationDetails)) {
			return "";
		}

		WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;
		return webDetails.getRemoteAddress();
	}

	/**
	 * 判断用户是否拥有角色, 如果用户拥有参数中的任意一个角色则返回true.
	 */
	public static boolean hasAnyRole(String... roles) {
		Authentication authentication = getAuthentication();

		if (authentication == null) {
			return false;
		}

		Collection<GrantedAuthority> grantedAuthorityList = (Collection<GrantedAuthority>) authentication.getAuthorities();

		for (String role : roles) {
			for (GrantedAuthority authority : grantedAuthorityList) {
				if (role.equals(authority.getAuthority())) {
					return true;
				}
			}
		}

		return false;
	}

}
